<?php
/**
 * UserRepo.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-10 14:44:54
 * @modified   2023-05-10 14:44:54
 */

namespace Beike\Seller\Repositories;

use Beike\Seller\Http\Resources\UserDetail;
use Beike\Seller\Models\SellerUser;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Permission;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;

class UserRepo
{
    /**
     * 获取后台用户管理员列表
     */
    public static function getUsers(): array
    {
        $sellerId   = current_seller_user()->seller_id;
        $builder    = SellerUser::query()->where('seller_id', $sellerId);
        $users      = $builder->get();

        return UserDetail::collection($users)->jsonSerialize();
    }

    /**
     * @param $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function find($id)
    {
        $sellerId = current_seller_user()->seller_id;

        return SellerUser::query()->where('seller_id', $sellerId)->find($id);
    }

    /**
     * 创建后台管理员用户
     *
     * @param $data
     * @return SellerUser
     * @throws \Exception
     */
    public static function createUser($data): SellerUser
    {
        $sellerId = current_seller_user()->seller_id;
        $user     = new SellerUser([
            'seller_id'            => $sellerId,
            'seller_user_group_id' => 0,
            'name'                 => $data['name'],
            'email'                => $data['email'],
            'password'             => bcrypt($data['password']),
            'locale'               => $data['locale'],
            'status'               => true,
        ]);
        $user->save();
        if (isset($data['permissions'])) {
            self::syncPermissions($user, $data['permissions']);
        }

        return $user;
    }

    /**
     * 同步所有权限
     *
     * @param SellerUser $user
     * @param $permissions
     * @throws \Exception
     */
    private static function syncPermissions(SellerUser $user, $permissions): void
    {
        if ($user->is_root) {
            return;
        }
        $allPermission = (new PermissionRepo())->getPermissions();
        $items         = [];
        foreach ($allPermission as $groupedPermissions) {
            foreach ($groupedPermissions['permissions'] as $groupedPermission) {
                if (in_array($groupedPermission['code'], $permissions)) {
                    $code = $groupedPermission['code'];
                    Permission::findOrCreate($code);
                    $items[] = $code;
                }
            }
        }
        if (empty($items)) {
            throw new \Exception(trans('seller::common.permission.select_one_at_least'));
        }
        $user->syncPermissions($items);
    }

    /**
     * 更新后台管理员用户
     *
     * @param $id
     * @param $data
     * @return Builder|Builder[]|Collection|Model|void|null
     */
    public static function updateUser($id, $data)
    {
        $sellerId  = current_seller_user()->seller_id;
        $password  = $data['password'] ?? '';
        $user      = SellerUser::query()->findOrFail($id);
        if ($user->seller_id != $sellerId) {
            return;
        }
        $userData  = [
            'name'   => $data['name'],
            'email'  => $data['email'],
            'locale' => $data['locale'],
            'active' => true,
        ];
        if ($password) {
            $userData['password'] = bcrypt($password);
        }
        $user->update($userData);
        // 编辑的时候有可能编辑的是根用户，不需要传权限
        if (isset($data['permissions'])) {
            self::syncPermissions($user, $data['permissions']);
        }

        return $user;
    }

    /**
     * 修改商户子账号密码
     * @param $id
     * @param $password
     * @return bool
     */
    public static function changePassword($user, $password)
    {
        if (! $user instanceof SellerUser) {
            $user = SellerUser::query()->findOrFail($user);
        }
        $user->password = bcrypt($password);
        $user->save();

        return true;
    }

    /**
     * 删除后台用户
     *
     * @param $id
     * @throws \Exception
     */
    public static function deleteUser($id)
    {
        $sellerId = current_seller_user()->seller_id;
        $user     = SellerUser::query()->findOrFail($id);
        if ($user->seller_id != $sellerId) {
            return;
        }
        if ($user->is_root) {
            throw new NotAcceptableHttpException(trans('admin/customer.cannot_delete_root'));
        }
        $user->delete();
    }
}
